package com.example.myapplication8_5;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toast currentToast = null; // 用于保存当前的 Toast 实例

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = findViewById(R.id.listView);

        // 数据准备
        List<Fruit> fruitList = new ArrayList<>();
        fruitList.add(new Fruit("红苹果", R.drawable.apple));
        fruitList.add(new Fruit("香橙", R.drawable.orange));
        fruitList.add(new Fruit("黑李子", R.drawable.blackplum));
        fruitList.add(new Fruit("柠檬", R.drawable.lemon));
        fruitList.add(new Fruit("梨子", R.drawable.pear));
        fruitList.add(new Fruit("草莓", R.drawable.strawberry));
        fruitList.add(new Fruit("香蕉", R.drawable.banana));
        fruitList.add(new Fruit("西瓜", R.drawable.watermelon));
        fruitList.add(new Fruit("猕猴桃", R.drawable.kiwi));
        fruitList.add(new Fruit("樱桃", R.drawable.cherry));

        // 设置适配器
        FruitAdapter adapter = new FruitAdapter(this, fruitList);
        listView.setAdapter(adapter);

        // 设置点击事件监听器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit selectedFruit = fruitList.get(position);

                // 如果当前有正在显示的 Toast，则取消它
                if (currentToast != null) {
                    currentToast.cancel();
                }

                // 创建自定义 Toast 布局
                LayoutInflater inflater = getLayoutInflater();
                View toastLayout = inflater.inflate(R.layout.custom_toast, null);

                // 设置图片和文字
                ImageView imageView = toastLayout.findViewById(R.id.toastImage);
                TextView textView = toastLayout.findViewById(R.id.toastText);
                imageView.setImageResource(selectedFruit.getImageResId());
                textView.setText(selectedFruit.getName());

                // 创建并显示新的 Toast
                currentToast = new Toast(MainActivity.this);
                currentToast.setDuration(Toast.LENGTH_SHORT); // 设置显示时长
                currentToast.setView(toastLayout); // 设置自定义布局
                currentToast.show(); // 显示 Toast
            }
        });
    }
}